package com.frxuexi.shop

import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.databinding.DataBindingUtil
import androidx.paging.PagingDataAdapter
import androidx.recyclerview.widget.DiffUtil.ItemCallback
import androidx.recyclerview.widget.RecyclerView.ViewHolder
import com.frxuexi.lib_base.GlideUtil
import com.frxuexi.lib_base.entity.ProductBeanItem
import com.frxuexi.shop.databinding.ItemShopBinding

class ShopPageAdapter:PagingDataAdapter<ProductBeanItem,ShopPageAdapter.MyViewHolder>(diffutill) {

    companion object{
        val diffutill=object :ItemCallback<ProductBeanItem>(){
            override fun areItemsTheSame(
                oldItem: ProductBeanItem,
                newItem: ProductBeanItem
            ): Boolean {
                return oldItem.id==newItem.id
            }

            override fun areContentsTheSame(
                oldItem: ProductBeanItem,
                newItem: ProductBeanItem
            ): Boolean {
                return oldItem==newItem
            }

        }
    }
    var mOnItemClickListener:OnItemClickListener? = null
    private var mOnItemLongClickListener: OnItemLongClickListener? = null
    class MyViewHolder(itemView:View):ViewHolder(itemView){
        val binding:ItemShopBinding=DataBindingUtil.bind(itemView)!!
    }

    override fun onBindViewHolder(holder: MyViewHolder, position: Int) {
        val productBeanItem = getItem(position)!!
        holder.binding.apply {
            shopName.setText(productBeanItem.storeName)
            shopPrice.setText(productBeanItem.price)
            GlideUtil.loadRoundImg(productBeanItem.image,ivShop)
        }
        holder.itemView.setOnClickListener {
            mOnItemClickListener?.onItemClick(position,productBeanItem)
        }
        holder.itemView.setOnLongClickListener {
            mOnItemLongClickListener?.onItemLongClick(productBeanItem)
            return@setOnLongClickListener true
        }
    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): MyViewHolder {
        val view = LayoutInflater.from(parent.context).inflate(R.layout.item_shop, parent, false)
        return MyViewHolder(view)
    }

    fun setOnItemClickListener(listener: OnItemClickListener){
        this.mOnItemClickListener=listener
    }

    fun setOnItemLongClickListener(listener: OnItemLongClickListener?) {
        this.mOnItemLongClickListener = listener
    }
}

interface OnItemClickListener{
    fun onItemClick(position: Int,item:ProductBeanItem)
}

interface OnItemLongClickListener{
    fun onItemLongClick(item:ProductBeanItem)
}

